﻿using System;
using System.Collections.Generic;
using System.Collections;

using System.Web;
using System.Web.UI;
using System.Data;
using System.Web.UI.WebControls;

public partial class admin_Company_Info : System.Web.UI.Page
{
    public ArrayList accountarr = null;
    public ArrayList accbank = null;
    public int id = 0, acc = 0;
    public int bank = 0;
    public bool neww = false;
    string mod = "";
    public bool enable = false;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["user"] == null) { Response.Redirect("../Index.aspx"); }

        if (!Page.IsPostBack)
        {
            LinkButton17.Visible = false;//estos son los botones de editar y eliminar
            LinkButton19.Visible = false;//
            lb_error.Visible = false;//el label del error
            llenobank();// llena el dropdownlist del banco

            if (Request.QueryString["bank"] != null) bank = int.Parse(Request.QueryString["bank"].ToString());//la variable que uilizara para llamar los datos
            if (Request.QueryString["id"] != null) id = int.Parse(Request.QueryString["id"].ToString());
            if (Request.QueryString["new"] != null) neww = bool.Parse(Request.QueryString["new"].ToString());
            else Session["tabc"] = null;        

            if (neww == true)
            {
                int tab = 0;
                if (Session["tabc"] != null) tab = (int)Session["tabc"];
                if (tab == 0)
                {
                    Session["tabc"] = validarTab(0);
                    LinkButton15_ModalPopupExtender.Show();
                }
                else { validarTab(tab); }
            }

            //*************************** COMPANY INFO & LOCATION *****************************
            lb_companyid.Text = id.ToString();
            llenocountries();
            RE_GenericBean company = DB.getCompania(id);
            lb_companyid.Text = company.intC1.ToString();
            tb_companyname.Text = company.strC1.ToUpper();
            tb_nit.Text = company.strC2;
            tb_address1.Text = company.strC3.ToUpper();
            tb_address2.Text = company.strC4.ToUpper();
            tb_city.Text = company.strC5.ToUpper();
            tb_state.Text = company.strC6.ToUpper();
            tb_zip.Text = company.strC7;
            cb_country.SelectedValue = company.intC2.ToString();
            tb_phone1.Text = company.strC9;
            tb_phone2.Text = company.strC10;
            tb_phone3.Text = company.strC11;
            tb_fax.Text = company.strC12;
            tb_website.Text = company.strC13.ToUpper();
            tb_contactemail.Text = company.strC14.ToUpper();
            logo.ImageUrl = company.strC15;

            personalizarForm(company.intC2);

            tb_noaccount.Text = DB.getCountAccount(id).ToString();
            tb_numberemployees.Text = DB.getCountEmployee(id).ToString();

            if (company.intC1 != 0)
            {
                habilitocampos(false);
                habilitocampos3(false);
            }
            //**********************************************************************************

            //**************************** CLIENT ACCOUNTS *************************************
            accountarr = (ArrayList)DB.getArrCuenta(" WHERE tcu_tco_id = " + id);

            if (Request.QueryString["acc"] != null) acc = int.Parse(Request.QueryString["acc"].ToString());
            llenocompanias();
            lb_cuentaid.Text = acc.ToString();
            RE_GenericBean cuenta = DB.getCuenta(acc);
            lb_cuentaid.Text = cuenta.intC1.ToString();
            ddl_company.SelectedValue = cuenta.intC2.ToString();
            tb_accountname.Text = cuenta.strC1;
            tb_accountdesc.Text = cuenta.strC2;
            tb_operationmanager.Text = cuenta.strC3;
            tb_ho.Text = cuenta.decC1.ToString();
            if (Request.QueryString["new"] != null && Request.QueryString["id"] != null)
                if (bool.Parse(Request.QueryString["new"]) == true)
                    ddl_company.SelectedValue = Request.QueryString["id"];

            if (cuenta.intC1 != 0)
            {
                habilitocampos2(false);
                HyperLink1_ModalPopupExtender.Show();
            }
            tb_numberemployee.Text = DB.getCountEmployeebyCuenta(acc).ToString();
            //**********************************************************************************
            llenardocumentos();
            enableDocuments(false);

            pempdoc.Controls.Add(llenarDocEmp());

            //**************************** COMPANY ACCOUNTS *************************************

            accbank = (ArrayList)DB.getArrCuentasbyCompany(id);// llena la tabla en el formulario con los datos en la base de datos

            RE_GenericBean companybank = DB.getCuentasbyCompania(bank);// los valores de la tabla los muestra en el pop up
            if (companybank.intC1 != null) lb_accbank.Text = companybank.intC1.ToString();
            if (companybank.intC2 != null) DropDownList5.SelectedValue = companybank.intC2.ToString();
            DropDownList6.SelectedValue = companybank.strC2;
            TextBox1.Text = companybank.strC1.ToString();

            if (companybank.intC3 == 1)
            {
                CheckBox1.Checked = true;
            }
            if (companybank.intC1 != 0)
            {
                HyperLink2_ModalPopupExtender.Show();
                habilitocampos4(false);

                LinkButton17.Visible = true;
                LinkButton19.Visible = true;


            }
            //**********************************************************************************
        }
        else
        {
            id = int.Parse(lb_companyid.Text.ToString());
            acc = int.Parse(lb_cuentaid.Text);
            accountarr = (ArrayList)DB.getArrCuenta(" WHERE tcu_tco_id = " + id);
            accbank = (ArrayList)DB.getArrCuentasbyCompany(id);
            if (Request.QueryString["new"] != null) neww = bool.Parse(Request.QueryString["new"].ToString());
            lb_error.Visible = false;// esconde el error del pop up
            if (neww == true) { validarTab((int)Session["tabc"]); }
            personalizarForm(int.Parse(cb_country.SelectedValue));
            pempdoc.Controls.Add(llenarDocEmp());
            ddl_company.SelectedValue = id.ToString();
        }
    }

    private int validarTab(int tab)
    {
        if (tab == 0)//Company Info
        { TP1.Visible = true; TP2.Visible = false; TP3.Visible = false; TP4.Visible = false; TP5.Visible = false; pemppermit.Visible = false; PnlAddAccount.Visible = false; pnlAddType.Visible = false; LinkButton10.Visible = true; TabCointainer1.ActiveTabIndex = 0; }
        if (tab == 1)//Location
        { TP2.Visible = true; TP3.Visible = false; TP4.Visible = false; TP5.Visible = false; pemppermit.Visible = false; PnlAddAccount.Visible = false; pnlAddType.Visible = false; LinkButton12.Visible = true; LinkButton10.Visible = false; LinkButton3.Visible = false; TabCointainer1.ActiveTabIndex = 1; }
        if (tab == 2)//Client Account
        { TP4.Visible = true; TP3.Visible = false; TP5.Visible = false; pemppermit.Visible = false; PnlAddAccount.Visible = false; pnlAddType.Visible = true; LinkButton10.Visible = false; LinkButton3.Visible = false; LinkButton12.Visible = false; LinkButton13.Visible = true; TabCointainer1.ActiveTabIndex = 2; }
        if (tab == 3)//Documents
        { TP1.Visible = true; TP2.Visible = true; TP4.Visible = true; TP3.Visible = true; TP5.Visible = false; pemppermit.Visible = true; PnlAddAccount.Visible = false; LinkButton10.Visible = false; LinkButton3.Visible = false; LinkButton12.Visible = false; LinkButton13.Visible = false; bt_save_doc.Visible = true; bt_edit_doc.Visible = false; bt_upload_doc.Visible = true; llenardocumentos(); enableDocuments(true); TabCointainer1.ActiveTabIndex = 3; }
        if (tab == 4)//Banks
        { TP5.Visible = true; PnlAddAccount.Visible = true; bt_save_doc.Visible = false; LinkButton20.Visible = true; TabCointainer1.ActiveTabIndex = 4; }
        return tab;
    }

    private void llenocountries()
    {
        ArrayList companyarr = null;
        ListItem item = null;
        try
        {
            companyarr = (ArrayList)DB.getArrCountries("");
            if (companyarr != null && companyarr.Count > 0)
            {
                foreach (RE_GenericBean company in companyarr)
                {
                    item = new ListItem(company.strC1, company.intC1.ToString());

                    cb_country.Items.Add(item);
                }
            }
        }
        catch (Exception err)
        {
            utility.log(err.StackTrace);
        }
    }

    private void llenocompanias()
    {
        ArrayList companyarr = null;
        ListItem item = null;
        try
        {
            companyarr = (ArrayList)DB.getArrCompania("");
            if (companyarr != null && companyarr.Count > 0)
            {
                foreach (RE_GenericBean company in companyarr)
                {
                    item = new ListItem(company.strC1, company.intC1.ToString());
                    ddl_company.Items.Add(item);
                }
            }
        }
        catch (Exception err)
        {
            utility.log(err.StackTrace);
        }
    }
    
    private void habilitocampos(bool estado)
    {
        tb_companyname.Enabled = estado;
        //tb_companyname.Enabled = estado;
        tb_contactemail.Enabled = estado;
        tb_fax.Enabled = estado;
        //tb_noaccount.Enabled = estado;
        //tb_numberemployees.Enabled = estado;
        tb_phone1.Enabled = estado;
        tb_phone2.Enabled = estado;
        tb_phone3.Enabled = estado;
        tb_nit.Enabled = estado;
        tb_website.Enabled = estado;
        
    }

    private void habilitocampos3(bool estado)
    {
        tb_city.Enabled = estado;
        //cb_country.Enabled = estado;
        tb_state.Enabled = estado;
        tb_zip.Enabled = estado;
        tb_address1.Enabled = estado;
        tb_address2.Enabled = estado;
    }

    private void habilitocampos2(bool estado)
    {
        tb_accountdesc.Enabled = estado;
        tb_accountname.Enabled = estado;
        //tb_numberemployee.Enabled = estado;
        tb_operationmanager.Enabled = estado;
        ddl_company.Enabled = estado;
    }

    private void habilitocampos4(bool estado)
    {
        //se usa para habilitar o deshabilitar los campos en el pop up
        TextBox1.Enabled = estado;
        DropDownList5.Enabled = estado;
        DropDownList6.Enabled = estado;
        CheckBox1.Enabled = estado;

    }

    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        RE_GenericBean company = new RE_GenericBean();
        bool edit = false;

        company.intC1 = int.Parse(lb_companyid.Text);
        company.strC1 = tb_companyname.Text.ToUpper().Trim();
        company.strC2 = tb_nit.Text.ToUpper().Trim();
        company.strC3 = tb_address1.Text.ToUpper().Trim();
        company.strC4 = tb_address2.Text.ToUpper().Trim();
        company.strC5 = tb_city.Text.ToUpper().Trim();
        company.strC6 = tb_state.Text.ToUpper().Trim();
        company.strC7 = tb_zip.Text.ToUpper().Trim();
        company.intC2 = int.Parse(cb_country.SelectedValue);
        company.strC9 = tb_phone1.Text.Trim();
        company.strC10 = tb_phone2.Text.Trim();
        company.strC11 = tb_phone3.Text.Trim();
        company.strC12 = tb_fax.Text.Trim();
        company.strC13 = tb_website.Text.ToUpper().Trim();
        company.strC14 = tb_contactemail.Text.ToUpper().Trim();


        if (cb_country.SelectedValue != "0" && !tb_companyname.Text.Equals("") && !tb_nit.Text.Equals("") && !tb_phone1.Text.Equals("") && !tb_fax.Text.Equals("") && !tb_website.Text.Equals("") && !tb_contactemail.Text.Equals("") && !tb_city.Text.Equals("") && !tb_state.Text.Equals("") && !tb_zip.Text.Equals("") && !tb_address1.Text.Equals(""))
        {
            if (company.intC1 != 0) edit = true;
            if (DB.InsertaCompanyInfoGeneral(company, edit))
            {
                if (neww)
                {
                    int auxID = (DB.getIDCompany() - 1);
                    Session["tabc"] = validarTab(2);
                    Response.Redirect("Company_Info.aspx?id="+auxID+"&new=true");
                }
                else
                    Response.Redirect("Company_Info.aspx?id=" + id);
            }
        }
        else
        {
            Session["tabc"] = validarTab(1);
            logo.Visible = false;
            Response.Write("<script> alert('Warning. Fill required fields! ');</script>");
        }
    }

    protected void LinkButton2_Click(object sender, EventArgs e)
    {
        habilitocampos(true);
    }

    protected void LinkButton3_Click(object sender, EventArgs e)
    {
        id = int.Parse(lb_companyid.Text);
        if (id != 0)
        {
            int result = DB.DeleteConpania(id);
            Response.Redirect("CompanyInfo_General.aspx");
        }
    }
    protected void btnCuentaCancelar_Click(object sender, EventArgs e)
    {
        Response.Redirect("CompanyInfo_General.aspx");
    }
    protected void LinkButton4_Click(object sender, EventArgs e)
    {
        RE_GenericBean accounts = new RE_GenericBean();
        bool edit = false;
        accounts.intC1 = int.Parse(lb_cuentaid.Text);
        accounts.intC2 = int.Parse(ddl_company.SelectedValue.ToString());
        accounts.strC1 = tb_accountname.Text.Trim().ToUpper();
        accounts.strC2 = tb_accountdesc.Text.Trim().ToUpper();
        accounts.strC3 = tb_operationmanager.Text.Trim().ToUpper();
        accounts.decC1 = Decimal.Parse(tb_ho.Text.Trim());
        if (accounts.intC1 != 0) edit = true;

        if(tb_accountname.Text!=""&&ddl_company.SelectedValue!="0")
            if (DB.InsertAccount(accounts, edit))
            {
                string IDN = "";
                if (Request.QueryString["new"] != null) { IDN = "&new=true"; }
                habilitocampos2(false);
                Response.Redirect("Company_Info.aspx?id=" + id + IDN);
            }
    }
    protected void LinkButton5_Click(object sender, EventArgs e)
    {
        habilitocampos2(true);
        HyperLink1_ModalPopupExtender.Show();
    }
    protected void LinkButton6_Click(object sender, EventArgs e)
    {
        int acc = int.Parse(lb_cuentaid.Text);
        if (acc != 0)
        {
            int result = DB.DeleteCuenta(acc);
            Response.Redirect("Company_Info.aspx?id=" + id);
        }
    }
    protected void LinkButton7_Click(object sender, EventArgs e)
    {
        //Response.Redirect("Company_Info.aspx?id=" + id);
        HyperLink1_ModalPopupExtender.Hide();
        if (neww == true)
            Response.Redirect(Request.UrlReferrer.ToString());
        else
            Response.Redirect("Company_Info.aspx?id=" + id);
    }
    protected void LinkButton8_Click(object sender, EventArgs e)
    {
    }
    protected void LinkButton10_Click(object sender, EventArgs e)
    {
        if (!tb_companyname.Text.Equals("") && !tb_nit.Text.Equals("") && !tb_phone1.Text.Equals("") && !tb_fax.Text.Equals("") && !tb_website.Text.Equals("") && !tb_contactemail.Text.Equals(""))
        {
            //Response.Redirect("Company_Info.aspx?new=true&mod=lt");
            Session["tabc"] = validarTab(1);
        }
        else
        {
            Session["tabc"] = validarTab(0);
            Response.Write("<script> alert('Warning. Fill required fields! ');</script>");
        }
    }
    protected void LinkButton12_Click(object sender, EventArgs e)
    {
        if (cb_country.SelectedValue != "0" && !tb_city.Text.Equals("") && !tb_state.Text.Equals("") && !tb_zip.Text.Equals("") && !tb_address1.Text.Equals(""))
        {
            Response.Redirect("Company_Info.aspx?new=true&mod=ca");
        }
        else
        {
            Response.Write("<script> alert('Warning. Fill required fields! ');</script>");
        }
    }
    protected void LinkButton9_Click(object sender, EventArgs e)
    {
        habilitocampos3(true);
    }
    protected void LinkButton11_Click(object sender, EventArgs e)
    {
        Response.Redirect("CompanyInfo_General.aspx");
    }
    protected void LinkButton13_Click(object sender, EventArgs e)
    {
        Session["tabc"] = validarTab(3);
    }

    private void personalizarForm(int country)
    {
        //***************** Company Info ****************************************
        
        RE_GenericBean tax = utility.getControl(country, "label", lb_nit.ID);
        if (tax != null) lb_nit.Text = tax.strC1;

        /*RE_GenericBean phone = utility.getControl(country, "exp_regular", "rg_phone");
        if (phone != null)
        {
            rg_phone1.ErrorMessage = phone.strC1; rg_phone1.ValidationExpression = phone.strC2;
            rg_phone2.ErrorMessage = phone.strC1; rg_phone2.ValidationExpression = phone.strC2;
            rg_phone3.ErrorMessage = phone.strC1; rg_phone3.ValidationExpression = phone.strC2;
            rg_phone4.ValidationExpression = phone.strC2;
        }*/

        RE_GenericBean web = utility.getControl(country, "exp_regular", rg_website.ID);
        if (web != null) { rg_website.ErrorMessage = web.strC1; rg_website.ValidationExpression = web.strC2; }

        RE_GenericBean email = utility.getControl(country, "exp_regular", rg_email.ID);
        if (email != null) { rg_email.ErrorMessage = email.strC1; rg_email.ValidationExpression = email.strC2; }

        //RE_GenericBean nit = utility.getControl(country, "exp_regular", rg_nit.ID);
        //if (nit != null) { rg_nit.ErrorMessage = nit.strC1; rg_nit.ValidationExpression = nit.strC2; }

        //************************************************************************
        //******************* Location *******************************************
        RE_GenericBean state = utility.getControl(country, "label", lb_state.ID);
        if (state != null) lb_state.Text = state.strC1;

        RE_GenericBean zip = utility.getControl(country, "label", lb_zipcode.ID);
        if (zip != null) lb_zipcode.Text = zip.strC1;

        RE_GenericBean zip2 = utility.getControl(country, "exp_regular", rg_zip.ID);
        if (zip2 != null) { rg_zip.ErrorMessage = zip2.strC1; rg_zip.ValidationExpression = zip2.strC2; }
        //************************************************************************
    }
    protected void lnk_gua_Click(object sender, EventArgs e)
    {
        cb_country.SelectedValue = "1";
        personalizarForm(1);
    }
    protected void lnk_usa_Click(object sender, EventArgs e)
    {
        cb_country.SelectedValue = "2";
        personalizarForm(2);
    }
    protected void lnk_mx_Click(object sender, EventArgs e)
    {
        cb_country.SelectedValue = "3";
        personalizarForm(3);
    }
    protected void LinkButton14_Click(object sender, EventArgs e)
    {
        LinkButton15_ModalPopupExtender.Hide();
        Response.Redirect("CompanyInfo_General.aspx");
    }

    public DataTable getDocuments()
    {
        ArrayList companyarr = null;
        DataTable dt = null;
        try
        {
            companyarr = (ArrayList)DB.getArrDocsComp();
            if (companyarr != null && companyarr.Count > 0) { dt = utility.getDataTableDocuments(companyarr); }
        }
        catch (Exception err) { utility.log(err.StackTrace); }
        return dt;
    }

    private void enableDocuments(bool p)
    {
        if (gv_documents.Rows.Count > 0)
        {
            foreach (GridViewRow ROW in gv_documents.Rows)
            {
                int con = ROW.Controls.Count;
                DropDownList ddl = (DropDownList)ROW.FindControl("ddl_document");
                FileUpload fu = (FileUpload)ROW.FindControl("fu_document");
                ImageButton ln = (ImageButton)ROW.FindControl("ln_view");
                ddl.Enabled = p;
                fu.Enabled = p;
                ln.Enabled = true;
            }
        }
    }

    protected void deletedocument(object sender, EventArgs e)
    {
        int index = 0;
        ImageButton bt = (ImageButton)sender;
        GridViewRow objFila = (GridViewRow)bt.Parent.Parent;

        index = objFila.RowIndex;
        int i = 0;
        foreach (GridViewRow ROW in gv_documents.Rows)
        {
            if (i == index)
            {
                int con = ROW.Controls.Count;

                Label lbid = (Label)ROW.FindControl("lb_iddocemp");
                Label lbidtipodoc = (Label)ROW.FindControl("lb_iddoc");
                int id = int.Parse(lbid.Text);
                int tempidtipodoc = DB.getIdNombreTipoDoc("Photo");

                int res = DB.DeleteDocumentoCom(id);
                if (res == 1)
                {
                    if (lbidtipodoc.Text.Equals(tempidtipodoc.ToString()))
                    {
                        //photo.ImageUrl = "images/no-user-picture-set.png";
                    }
                    llenardocumentos();
                    enableDocuments(enable);
                }
                else
                {
                }
            }

            i++;
        }

    }

    protected void gv_documents_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            Label label = (Label)e.Row.FindControl("lb_obligatorio");
            if (label.Text.Equals("1")) { label.Text = "*"; label.ForeColor = System.Drawing.Color.Red; }
            else { label.Text = "*"; label.ForeColor = System.Drawing.Color.White; }

            Label label2 = (Label)e.Row.FindControl("lb_path");
            if (label2 != null && !label2.Text.Equals(""))
            {
                ImageButton imagen = (ImageButton)e.Row.FindControl("ln_view");
                imagen.OnClientClick = "javascript:window.open('../data/documents/" + label2.Text + "');";
                imagen.Visible = true;
            }
        }
    }
    protected void bt_save_doc_Click(object sender, EventArgs e)
    {
        Session["tabc"] = validarTab(4);        
    }
    protected void bt_edit_Click(object sender, EventArgs e)
    {
        enableDocuments(true);
        if (TabCointainer1.ActiveTabIndex == 3) { bt_upload_doc.Visible = true; }
    }
    protected void bt_cancel_Click(object sender, EventArgs e)
    {
        if (neww == true)
            Response.Redirect(Request.UrlReferrer.ToString());
        else
            Response.Redirect("Company_Info.aspx?id=" + id);
    }
    protected void bt_upload_doc_Click(object sender, EventArgs e)
    {
        if (bt_save_doc.Visible == true && bt_save_doc.Enabled == true) bt_save_doc.Enabled = false;
        foreach (GridViewRow ROW in gv_documents.Rows)
        {
            FileUpload fu = (FileUpload)ROW.FindControl("fu_document");

            if (fu != null && fu.PostedFile != null)
            {
                string filepath = fu.FileName;
                if (filepath != "")
                {
                    string[] ext = filepath.Split('.');
                    DropDownList ddlphoto = (DropDownList)ROW.FindControl("ddl_document");

                    Label lbid = (Label)ROW.FindControl("lb_iddoc");
                    Label lbiddoc = (Label)ROW.FindControl("lb_iddocemp");
                    RE_GenericBean re = new RE_GenericBean();
                    ImageButton hy = (ImageButton)ROW.FindControl("ln_view");
                    re.intC1 = id;
                    re.intC2 = int.Parse(lbid.Text);
                    re.intC5 = int.Parse(lbiddoc.Text);

                    bool actualiza = false;
                    if (re.intC5 != 0) actualiza = true;
                    RE_GenericBean res = DB.InsertaDocumentoCom(re, actualiza);
                    if (res.intC1 == 1 && res.intC2 != 0)
                    {
                        string horatemp = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour + DateTime.Now.Minute.ToString();
                        re.intC5 = res.intC2;
                        fu.PostedFile.SaveAs(Server.MapPath("~//data//documents//doc_" + re.intC5 + "_" + lbid.Text + "_user_" + re.intC1 + "_" + horatemp + "." + ext[1]));
                        re.strC1 = "doc_" + re.intC5 + "_" + lbid.Text + "_user_" + re.intC1 + "_" + horatemp + "." + ext[1];
                        hy.OnClientClick = "javascript:window.open('../data/documents/" + re.strC1 + "');";
                        RE_GenericBean res2 = DB.InsertaDocumentoCom(re, true);
                        if (res2.intC1 == 1 && res2.intC2 != 0)
                        {
                            if (ddlphoto.SelectedItem.ToString().ToUpper().Equals("PHOTO"))
                            {
                                //photo.ImageUrl = "~/data/documents/" + re.strC1;
                            }
                        }
                    }
                }

            }
        }
        bt_edit_doc.Visible = true;
        bt_upload_doc.Visible = false;
        llenardocumentos();
        enableDocuments(false);
        if (bt_save_doc.Visible == true) bt_save_doc.Enabled = true;
    }

    private void llenardocumentos()
    {
        ArrayList arr2 = DB.getArrDocumentbyCom(id);
        DataTable dt2 = utility.getDataTableDocuments(arr2);
        gv_documents.DataSource = dt2;
        gv_documents.DataBind();

        foreach (DataRow dataRow in dt2.Rows)
        {
            string temp1 = dataRow[0].ToString();
            string temp2 = dataRow[1].ToString();
            string temp3 = dataRow[2].ToString();
            string temp4 = dataRow[3].ToString();
            string temp5 = dataRow[4].ToString();

            if (dataRow[1].ToString().ToUpper().Equals("PHOTO"))
            {
                //if (!dataRow[4].ToString().Equals("")) photo.ImageUrl = "~/data/documents/" + dataRow[4].ToString();
            }
        }
    }


    protected void lnk_addnewdoc_Click(object sender, EventArgs e)
    {
        if (fu_newdoc != null && fu_newdoc.PostedFile != null)
        {
            string filepath = fu_newdoc.FileName;
            if (filepath != "")
            {
                string[] ext = filepath.Split('.');
                RE_GenericBean re = new RE_GenericBean();
                re.intC1 = id;
                re.intC2 = int.Parse(ddl_newdoc.SelectedValue.ToString());
                re.intC5 = 0;

                bool actualiza = false;
                if (re.intC5 != 0) actualiza = true;
                RE_GenericBean res = DB.InsertaDocumento(re, actualiza);
                if (res.intC1 == 1 && res.intC2 != 0)
                {
                    re.intC5 = res.intC2;
                    string horatemp = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour + DateTime.Now.Minute.ToString();
                    fu_newdoc.PostedFile.SaveAs(Server.MapPath("~//data//documents//doc_" + re.intC5 + "_" + re.intC2 + "_user_" + re.intC1 + horatemp + "." + ext[1]));
                    re.strC1 = "doc_" + re.intC5 + "_" + re.intC2 + "_user_" + re.intC1 + horatemp + "." + ext[1];

                    RE_GenericBean res2 = DB.InsertaDocumento(re, true);
                    if (res2.intC1 == 1 && res2.intC2 != 0) { lnk_add_doc_ModalPopupExtender.Hide(); }
                    else{}
                }
            }
            llenardocumentos();
        }
    }
    protected void lnk_cancel_newdoc_Click(object sender, EventArgs e)
    {
        lnk_add_doc_ModalPopupExtender.Hide();
    }
    protected void lnk_add_doc_Click(object sender, EventArgs e)
    {

    }


    protected void LinkButton16_Click(object sender, EventArgs e)
    {
        LinkButton17.Visible = false;
        LinkButton19.Visible = false;

    }
    protected void LinkButton17_Click(object sender, EventArgs e)
    {//borra el registro deseado
        int cc = int.Parse(lb_accbank.Text);
        if (cc != 0)
        {
            int result = DB.DeleteCompanyAccount(cc);
            Response.Redirect("Company_Info.aspx?id=" + id);
        }
    }
    protected void LinkButton18_Click(object sender, EventArgs e)
    {
        if (neww == true)
            Response.Redirect(Request.UrlReferrer.ToString());
        else
            Response.Redirect("Company_Info.aspx?id=" + id);//redirecciona a la pagina de la compania
    }
    protected void LinkButton19_Click(object sender, EventArgs e)
    {
        if (TextBox1.Text == "" || DropDownList5.SelectedIndex == 0 || DropDownList6.SelectedIndex == 0)//esta es la validacion para que no deje guardar sin que se llenen los campos
        {
            lb_error.Visible = true;
            HyperLink2_ModalPopupExtender.Show();
        }
        else
        {
            RE_GenericBean combank = new RE_GenericBean();// aqui se guardan los valores en las variables para luego ser ingresadas a la tabla
            bool edit = false;

            int accbank;
            combank.strC1 = TextBox1.Text.Trim().ToUpper();
            combank.intC1 = DropDownList5.SelectedIndex;
            combank.strC2 = DropDownList6.SelectedValue;
            combank.intC2 = int.Parse(lb_companyid.Text);
            combank.intC4 = int.Parse(lb_accbank.Text);
            if (CheckBox1.Checked == true)
            {
                combank.intC3 = 1;
            }
            else
            {
                combank.intC3 = 0;
            }
            accbank = int.Parse(lb_accbank.Text);
            if (accbank != 0) edit = true;
            if (DB.InsertCompanyBank(combank, edit))
            {
                if (Request.QueryString["new"] != null)
                {
                    if (neww == true)
                        Response.Redirect("Company_Info.aspx?id=" + id + "&new=true");
                }
                else
                    Response.Redirect("Company_Info.aspx?id=" + id);
            }
        }
    }
    protected void LinkButton20_Click(object sender, EventArgs e)
    {
        habilitocampos4(true);//hace que los campos se habiliten
        HyperLink2_ModalPopupExtender.Show();//muestra el pop up
    }

    private void llenobank()
    {
        //muestra los valores de la tabla en el dropdownlist
        ArrayList accbank = null;
        ListItem item = new ListItem();
        item.Value = "0";
        item.Text = "Select one";

        DropDownList5.Items.Add(item);
        try
        {
            accbank = (ArrayList)DB.getArrCompanyBank("");
            if (accbank != null && accbank.Count > 0)
            {
                foreach (RE_GenericBean c in accbank)
                {
                    item = new ListItem(c.strC1, c.intC1.ToString());
                    DropDownList5.Items.Add(item);
                }
            }
        }
        catch (Exception err)
        {
            utility.log(err.StackTrace);
        }

    }
    protected void Button1_Click1(object sender, EventArgs e)
    {
        Response.Redirect("Company_Info.aspx");
    }
    protected void LinkButton20_Click1(object sender, EventArgs e)
    {
        Session["tabc"] = null;
        Response.Redirect("CompanyInfo_General.aspx");
    }

    private Table llenarDocEmp()
    {
        Table tabla = new Table();
        tabla.Width = 850;
        tabla.CellPadding = 0;
        tabla.CellSpacing = 0;
        tabla.Font.Size = 10;
        tabla.Font.Name = "Arial";

        Table tizq = new Table(); //tizq.Attributes.Add("Style", "border:2px solid Red;");
        Table tder = new Table(); //tder.Attributes.Add("Style", "border:2px solid Green;");
        TableRow rowtb = new TableRow();
        TableCell celltb1 = new TableCell();
        celltb1.Controls.Add(tizq);
        TableCell celltb2 = new TableCell();
        celltb2.Controls.Add(tder);
        rowtb.Cells.Add(celltb1); rowtb.Cells.Add(celltb2);

        tabla.Controls.Add(rowtb);
        //tabla.BorderWidth = 2;
        //tabla.BorderStyle = BorderStyle.Solid;

        ArrayList docs = DB.getDocumentosTipo(id, 2);
        int cont = 0;
        if (docs != null)
        {
            foreach (RE_GenericBean rg in docs)
            {
                cont++;
                //Nombre
                TableRow row = new TableRow();
                TableCell cell = new TableCell();
                cell.Width = 180;
                cell.HorizontalAlign = HorizontalAlign.Left;
                Label name = new Label();
                name.Text = rg.strC1;
                name.Font.Bold = true;
                cell.Controls.Add(name);
                //Obligatorio
                TableCell cell2 = new TableCell();
                cell2.Width = 90;
                CheckBox chobl = new CheckBox();
                chobl.ID = "ob" + rg.intC1;
                Label lbobl = new Label();
                lbobl.Text = "Mandatory";
                if (rg.intC2 == 1) chobl.Checked = true;
                cell2.Controls.Add(chobl); cell2.Controls.Add(lbobl);
                //Visible
                TableCell cell3 = new TableCell();
                cell3.Width = 80;
                CheckBox chvis = new CheckBox();
                chvis.ID = "vi" + rg.intC1;
                Label lbvis = new Label();
                lbvis.Text = "Visible";
                if (rg.intC3 == 1) chvis.Checked = true;
                cell3.Controls.Add(chvis); cell3.Controls.Add(lbvis);

                row.Cells.Add(cell); row.Cells.Add(cell2); row.Cells.Add(cell3);
                if ((cont % 2) != 0) tizq.Controls.Add(row);
                else tder.Controls.Add(row);
            }
        }
        return tabla;
    }
    protected void bt_docs_Click(object sender, EventArgs e)
    {
        ArrayList docs = DB.getDocumentosTipo2(2);
        if (docs != null)
        {
            foreach (RE_GenericBean rg in docs)
            {
                CheckBox ckobl = ((CheckBox)pempdoc.FindControl("ob" + rg.intC1));
                CheckBox ckvis = ((CheckBox)pempdoc.FindControl("vi" + rg.intC1));
                if (ckobl != null)
                    if (ckobl.Checked == true)//Obligatorio
                        rg.intC2 = 1;
                if (ckvis != null)
                    if (ckvis.Checked == true)//Visible
                        rg.intC3 = 1;
            }
            DB.insertDocsComp(docs, id);
        }
    }
}